package main

import (
	"log"
	"time"
)

func main() {
	rate := getBestRate2()
	log.Println("best rate is :", rate)
}

// 获取最优费率
func getBestRate2() int {
	defer func(start int64) {	//计算耗时
		log.Printf("getBestRate cost :%d ms", (time.Now().UnixNano() - start) / 1000000)
	}(time.Now().UnixNano())
	ch := make(chan int, 3)
	go getRateFromA2(ch)
	go getRateFromB2(ch)
	go getRateFromC2(ch)
	bestRate := 0
	for i := 0; i < 3; i++ {
		if i == 0 {
			bestRate = <- ch
			continue
		}
		rate := <- ch
		if rate < bestRate {
			bestRate = rate
		}
	}
	return bestRate
}

func getRateFromA2(ch chan int) {
	log.Println("start getRateFromA")
	time.Sleep(2 * time.Second)	//模拟耗时
	log.Println("end getRateFromA")
	rate := 2
	ch <- rate
}

func getRateFromB2(ch chan int) {
	time.Sleep(500 * time.Millisecond)	//模拟耗时
	rate := 5
	ch <- rate
}

func getRateFromC2(ch chan int) {
	log.Println("start getRateFromC")
	time.Sleep(3 * time.Second)
	log.Println("end getRateFromC")
	rate := 3
	ch <- rate
}
